/*
 * @Description: 区域组件
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2021-03-31 10:29:39
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 11:46:46
 */
import React, { RefObject, useImperativeHandle } from 'react';
import { DataSet, Tree } from 'choerodon-ui/pro';
import { NodeRenderer } from 'choerodon-ui/pro/lib/tree/util';
import { useDataSet, useDataSetEvent } from 'hzero-front/lib/utils/hooks';
import { reqSelectedAreaDateSet, reqCustomerDateSet } from '@src/stores/minOrderDtlDS';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import intl from 'utils/intl';
import { DataSetSelection, FieldType } from 'choerodon-ui/pro/lib/data-set/enum';
interface propType {
  areaDS: DataSet;
  treeStyle?: Object;
  parentDS?: any;
  ruleId: string | number;
  refFN?: RefObject<Object>;
  disabledFlag: boolean;
  tableDS?: DataSet;
}
const AreaTree: React.FC<propType> = ({
  areaDS,
  treeStyle,
  parentDS,
  ruleId,
  refFN,
  disabledFlag,
  tableDS,
}) => {
  const reqSelectedAreaDS = useDataSet(() => new DataSet(reqSelectedAreaDateSet() as DataSetProps));
  const reqCustomerDS = useDataSet(() => new DataSet(reqCustomerDateSet() as DataSetProps));

  useImperativeHandle(refFN, () => ({
    renderSelectedTreeFn: renderSelectedTree,
  }));

  const nodeRenderer: NodeRenderer = ({ record }) => {
    return record?.get('meaning') || record?.get('largeAreaCnName');
  };

  // 根据大区请求区域信息
  useDataSetEvent(parentDS, 'update', ({ dataSet, name }) => {
    if (name === 'regionId') {
      const regionId = dataSet.current.get('regionId');
      if (regionId) {
        areaDS.setQueryParameter('largeAreaId', regionId);
        areaDS.query().then(() => {
          // 勾上已选数据
          renderSelectedTree();
        });
      } else {
        areaDS.removeAll();
      }
    }
    if (name === 'amountRuleType' && dataSet.current.get('amountRuleType')) {
      setCustomerParam();
    }
  });

  // 请求头表后，根据大区请求区域信息
  useDataSetEvent(parentDS, 'load', ({ dataSet }) => {
    const regionId = dataSet.current.get('regionId');
    areaDS.setQueryParameter('largeAreaId', regionId);
    // 请求区域信息后，再请求已选区域
    areaDS.query().then(() => {
      // 勾上已选数据
      renderSelectedTree();
    });
  });

  // 请求已选区域
  const renderSelectedTree = () => {
    //请求已选区域
    reqSelectedAreaDS.setQueryParameter('ruleId', ruleId || parentDS.current.get('ruleId'));
    reqSelectedAreaDS.query().then(selectedList => {
      areaDS.forEach(areaRecord => {
        const areaValue = areaRecord.get('value');
        if (
          selectedList.some(item => {
            return item.countryId === Number(areaValue);
          })
        ) {
          // 展开 他的父节点展开
          areaRecord.set('check', true);
          areaRecord.parent?.set('expand', true);
          areaRecord.set('objectVersionNumber', selectedList[0].objectVersionNumber);
        }
      });
      setTimeout(() => {
        setCustomerParam();
      }, 10);
    });
  };

  const handleCheck = () => {
    tableDS?.forEach(record => {
      record.set('customerCode', null);
    });
    setCustomerParam();
  };

  // 代理商请求参数
  const setCustomerParam = () => {
    const parentCurrentRecord = parentDS.current;

    if (parentCurrentRecord?.get('amountRuleType') !== 'WHITE_LIST_RULES') {
      tableDS?.getField('customerCode')?.set('required', false);
      return;
    }
    const bigAreas = parentCurrentRecord?.get('regionId');
    // 国家
    const regions: number[] = [];
    // 小区
    const smallAreas: number[] = [];

    // 去重obj
    let obj = {};
    areaDS.forEach(record => {
      if (record.get('parentCodeValue') && record.get('check')) {
        regions.push(record?.get('value'));
        const key = record.get('parentCodeValue');
        if (!obj[key]) {
          smallAreas.push(key);
          obj[key] = key;
        }
      }
    });
    // 未勾选区域不请求
    if (!regions.length) return;
    if (!smallAreas.length) return;

    const smallAreasStr = smallAreas.join();
    const regionsStr = regions.join();

    reqCustomerDS.setQueryParameter('bigAreas', bigAreas);
    reqCustomerDS.setQueryParameter('smallAreas', smallAreasStr);
    reqCustomerDS.setQueryParameter('regions', regionsStr);
    reqCustomerDS.query().then(res => {
      tableDS?.addField('customerCode', {
        name: 'customerCode',
        type: FieldType.string,
        label: intl.get('dji.otc.om.view.field.customerTradeCode').d('交易身份客户'),
        options: getCustomerOptions(res),
        required: true,
      });
    });
    // const option = new DataSet({
    //   // paging: true,
    //   pageSize:100,
    //   selection: 'single' as DataSetSelection,
    //   autoQuery: true,
    //   transport: {
    //     read: config => {
    //       return {
    //         ...config,
    //         url: `${O2_OM}/v1/customer-interface/get-customer-trade-data?page=0&size=10&bigAreas=${bigAreas}&smallAreas=${smallAreasStr}&regions=${regionsStr}`,
    //         data: [],
    //         method: 'get',
    //         transformResponse: res => {
    //           return JSON.parse(res).content;
    //         },
    //       };
    //     },
    //   },
    // });
    // tableDS?.addField('customerCode', {
    //   name: 'customerCode',
    //   type: FieldType.string,
    //   label: intl.get('dji.otc.om.view.field.orderType').d('交易身份客户'),
    //   options: option,
    //   required: true,
    // });
  };

  // 获取交易身份option bigAreas, smallAreasStr, regionsStr
  const getCustomerOptions = res => {
    const option = new DataSet({
      paging: true,
      autoQuery: true,
      selection: 'single' as DataSetSelection,
      data: res.content,
    });
    return option;
  };

  return (
    <Tree
      style={treeStyle}
      dataSet={areaDS}
      checkable
      renderer={nodeRenderer}
      disabled={disabledFlag}
      onCheck={handleCheck}
    />
  );
};

export default AreaTree;
